package com.mi.common.core.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Long array deserializer
 *
 * @author jin_huaquan
 * @version 1.0
 * @date 2021/11/23 17:23
 */
public class LongArrayDeserializer extends JsonDeserializer<Long[]> {

    @Override
    public Long[] deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        if (Objects.isNull(jsonParser)) {
            return new Long[0];
        }
        JsonNode jsonNode = jsonParser.getCodec().readTree(jsonParser);

        List<Long> array = new ArrayList<>(16);

        jsonNode.elements().forEachRemaining(value -> array.add(Long.valueOf(value.asText())));

        return array.toArray(new Long[0]);
    }
}
